package com.smartwebee.android.blespp.hospital;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.smartwebee.android.blespp.BleSppActivity;
import com.smartwebee.android.blespp.DeviceScanActivity;
import com.smartwebee.android.blespp.R;
import com.smartwebee.android.blespp.hospital.fragment.SurveyFragment;
import com.smartwebee.android.blespp.utils.Utils;

import java.util.ArrayList;

import static com.smartwebee.android.blespp.utils.Utils.MODE_TYPE;

public class HospitalScanActivity extends BaseActivity {

    protected BluetoothAdapter mBluetoothAdapter;
    protected boolean mScanning;
    private static final int REQUEST_ENABLE_BT = 1;
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    protected HospitalScanAdapter adapter;
    protected ListView listView;
    private Button btnScan;

    // Device scan callback.
    protected BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isDeviceValid(device)) {
                                adapter.addItem(device);
                            }
                        }
                    });
                }
            };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hospital_scan);
        initView();
        initBluetooth();
        file = Utils.operationFile(this);
    }

    private boolean isDeviceValid(BluetoothDevice device) {
        return true;
//        return !TextUtils.isEmpty(device.getName()) &&
//                (device.getName().startsWith("ET11") || device.getName().startsWith("BLE") || device.getName().startsWith("TQ"));
    }

    private void initBluetooth() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.hospital_error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.hospital_error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mayRequestLocation();
    }

    private void initView() {
        findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        listView = (ListView)findViewById(R.id.listview);
        btnScan = (Button)findViewById(R.id.btn_scan);
        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mScanning) {
                    scanLeDevice(false);
                } else {
                    adapter.clear();
                    scanLeDevice(true);
                }
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final BluetoothDevice device = adapter.getItem(position);
                if (device == null) return;
                if (mScanning) {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    mScanning = false;
                    resetBtnText();
                }
                final Intent intent = new Intent(HospitalScanActivity.this, HospitalIndexActivity.class);

                //从计划跳转过来
                if (getIntent().hasExtra(Utils.PLAN_TYPE)) {
                    int typePosition = Utils.getPlanPosition(getIntent().getStringExtra(Utils.PLAN_TYPE));
                    intent.putExtra(Utils.TYPE_POSITION, typePosition);
                    intent.putExtra(Utils.CHILD_POSITION, 0);
                    intent.putExtra(MODE_TYPE, Utils.childItem.get(typePosition).get(0));
                } else {
                    //从项目跳转过来
                    intent.putExtra(MODE_TYPE, getIntent().getStringExtra(MODE_TYPE));
                }
                intent.putExtra(BleSppActivity.EXTRAS_DEVICE_NAME, device.getName());
                intent.putExtra(BleSppActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
                startActivity(intent);
            }
        });
    }

    private void mayRequestLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                //判断是否需要 向用户解释，为什么要申请该权限
                if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION))
                    Toast.makeText(this,R.string.ble_need_location, Toast.LENGTH_LONG).show();

                ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT && resultCode == 0) {
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
        // fire an intent to display a dialog asking the user to grant permission to enable it.
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }

        // Initializes list view adapter.
        adapter = new HospitalScanAdapter(this, new ArrayList<BluetoothDevice>());
        listView.setAdapter(adapter);
        scanLeDevice(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        scanLeDevice(false);
        adapter.clear();
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    resetBtnText();
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            resetBtnText();
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            resetBtnText();
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

    protected void resetBtnText() {
        if (mScanning) {
            btnScan.setText("停止搜索");
        } else {
            btnScan.setText("搜索");
        }
    }
}
